package com.shinemo.mpush.alloc.handler;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;

import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;

public class PageHandler implements HttpHandler{

	private byte[] data;

    public PageHandler(String path) {
        try (InputStream in = this.getClass().getResourceAsStream(path)) {
            this.data = new byte[in.available()];
            in.read(data);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void handle(HttpExchange httpExchange) throws IOException {
        if (data != null && data.length > 0) {
            httpExchange.getResponseHeaders().set("Content-Type", "text/html; charset=utf-8");
            httpExchange.sendResponseHeaders(200, data.length);//200, content-length
            OutputStream out = httpExchange.getResponseBody();
            out.write(data);
            out.close();
            httpExchange.close();
        } else {
            byte[] data = "404 Not Found".getBytes(StandardCharsets.UTF_8);
            httpExchange.getResponseHeaders().set("Content-Type", "text/plain; charset=utf-8");
            httpExchange.sendResponseHeaders(404, data.length);
            OutputStream out = httpExchange.getResponseBody();
            out.write(data);
            out.close();
            httpExchange.close();
        }
    }
}
